<template>
  <!-- 单行组件：文本、选择器、slot -->
  <div
    v-if="prefix && prefixWidth != 0"
    class="any-outsidebar"
  >
    <div
      :class="required ? 'any-prefix' : 'any-prefix2'"
      :style="prefixWidth ? 'min-width:' + prefixWidth + ';width:' + prefixWidth : ''"
    >
      {{ prefix }}
    </div>
    <!-- 自定义选项 -->
    <el-select
      v-if="type == 'select'"
      :style="selectStyle"
      v-model="elValue"
      :value-key="selectLabelkey"
      :filterable="selectFilterable"
      :placeholder="placeholder"
      :disabled="disabled"
      size="medium"
      @change="changeClick"
    >
      <el-option
        v-for="(item, index) in selectOption"
        :key="index"
        :label="item && typeof item == 'object' ? item[selectLabelkey] : item"
        :value="selectValuekey && item && typeof item == 'object' ? item[selectValuekey] : item"
      ></el-option>
    </el-select>
    <!-- 日期 -->
    <el-date-picker
      v-else-if="type == 'year' || type == 'month' || type == 'date' || type == 'datetime'"
      :style="selectStyle"
      v-model="elValue"
      :type="type"
      :picker-options="pickerOption"
      :placeholder="placeholder"
      :disabled="disabled"
      size="medium"
      @change="changeClick"
    ></el-date-picker>
    <!-- 时间 -->
    <el-time-picker
      v-else-if="type == 'time'"
      :style="selectStyle"
      v-model="elValue"
      :picker-options="elTimeOption"
      :placeholder="placeholder"
      :disabled="disabled"
      size="medium"
      @change="changeClick"
    ></el-time-picker>
    <!-- 时间间隔 -->
    <el-time-select
      v-else-if="type == 'timestep'"
      :style="selectStyle"
      v-model="elValue"
      :picker-options="elTimestepOption"
      :placeholder="placeholder"
      :disabled="disabled"
      size="medium"
      @change="changeClick"
    ></el-time-select>
    <!-- 地区 -->
    <el-cascader
      v-else-if="type == 'province' || type == 'city' || type == 'district'"
      :style="selectStyle"
      v-model="elValue"
      :options="areaArray"
      separator="-"
      :placeholder="placeholder"
      :disabled="disabled"
      size="medium"
      @change="changeClick"
    ></el-cascader>
    <!-- 扩展slot -->
    <slot name="suffix"></slot>
  </div>

  <!-- 单个选择器 -->
  <!-- 自定义选项 -->
  <el-select
    v-else-if="type == 'select'"
    :style="selectStyle"
    v-model="elValue"
    :value-key="selectLabelkey"
    :filterable="selectFilterable"
    :placeholder="placeholder"
    :disabled="disabled"
    size="medium"
    @change="changeClick"
  >
    <el-option
      v-for="(item, index) in selectOption"
      :key="index"
      :label="item && typeof item == 'object' ? item[selectLabelkey] : item"
      :value="selectValuekey && item && typeof item == 'object' ? item[selectValuekey] : item"
    ></el-option>
  </el-select>
  <!-- 日期 -->
  <el-date-picker
    v-else-if="type == 'year' || type == 'month' || type == 'date' || type == 'datetime'"
    :style="selectStyle"
    v-model="elValue"
    :type="type"
    :picker-options="pickerOption"
    :placeholder="placeholder"
    :disabled="disabled"
    size="medium"
    @change="changeClick"
  ></el-date-picker>
  <!-- 时间 -->
  <el-time-picker
    v-else-if="type == 'time'"
    :style="selectStyle"
    v-model="elValue"
    :picker-options="elTimeOption"
    :placeholder="placeholder"
    :disabled="disabled"
    size="medium"
    @change="changeClick"
  ></el-time-picker>
  <!-- 时间间隔 -->
  <el-time-select
    v-else-if="type == 'timestep'"
    :style="selectStyle"
    v-model="elValue"
    :picker-options="elTimestepOption"
    :placeholder="placeholder"
    :disabled="disabled"
    size="medium"
    @change="changeClick"
  ></el-time-select>
  <!-- 地区 -->
  <el-cascader
    v-else-if="type == 'province' || type == 'city' || type == 'district'"
    :style="selectStyle"
    v-model="elValue"
    :options="areaArray"
    separator="-"
    :placeholder="placeholder"
    :disabled="disabled"
    size="medium"
    @change="changeClick"
  ></el-cascader>
</template>

<script>
import anyfishUI from "../../index";
export default {
  name:"mm-select",
  props: {
    selectStyle: {// 选择框样式
      type: String,
      default: null
    },

    obj: {// InputObj
      type: Object,
      default: function () {
        return null;
      }
    },

    objKey: {// 数据对应InputObj的key值
      type: String,
      default: ""
    },

    prefix: {// 左边的文本内容
      type: String,
      default: null
    },

    prefixWidth: {// 左边的文本宽度：3.6rem、10px、20%等，为0则不显示，为空则自适应
      type: String,
      default: null
    },

    /**
     * 自定义选项（对应selectOption、selectLabelkey、selectValuekey）：select
     * 日期：year、month、date、datetime
     * 时间（对应timeOption）：time
     * 时间间隔（对应timestepOption、timestepMinute）：timestep
     * 地区：province、city、district
     */
    type: {
      type: String,
      default: "select"
    },

    selectOption: {// 对应select的数组
      type: Array,
      default: null
    },

    selectLabelkey: {// 对应select的数组的显示值的key
      type: String,
      default: null
    },

    selectValuekey: {// 对应select的数组的选中值的key
      type: String,
      default: null
    },

    selectFilterable: {// 对应select是否可搜索
      type: Boolean,
      default: false
    },

    timeOption: {// 对应time的时间限制
      type: [String, Array],
      default: "00:00:00-23:59:59"
    },

    timestepOption: {// 对应timestep的时间限制
      type: String,
      default: "00:00-23:59"
    },

    timestepMinute: {// 对应timestep的时间间隔的分钟数
      type: Number,
      default: 1
    },

    startLimitDate: {// 限制的开始日期，可为字符串、时间戳、date，单位秒
      type: Object | Date,
      default: null
    },

    endLimitDate: {// 限制的结束日期，可为字符串、时间戳、date，单位秒
      type: Object | Date,
      default: null
    },

    placeholder: {// 选择框为空时的提示文字
      type: String,
      default: null
    },

    required: {// 是否必填
      type: Boolean,
      default: false
    },

    disabled: {// 是否不可用
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      elValue: null,
      pickerOption: {
        disabledDate: (date) => {
          if (date) {
            let time = date.getTime();
            if (time > 0) {
              if (this.startLimitTime > 0 && this.startLimitTime > time) {
                return true;
              }
              if (this.endLimitTime > 0 && this.endLimitTime < time) {
                return true;
              }
            }
          }
          return false;
        }
      }
    }
  },

  computed: {
    elTimeOption() {
      if (this.type == "time") {
        if (this.timeOption) {
          return {
            selectableRange: this.timeOption.replace("-", " - ")
          }
        }
      }
      return null;
    },

    elTimestepOption() {
      if (this.type == "timestep") {
        let param = {};
        if (this.timestepOption) {
          let array = this.timestepOption.split("-");
          if (array.length == 2) {
            param.start = array[0];
            param.end = array[1];
          }
        }
        if (this.timestepMinute) {
          let hour = this.timestepMinute / 60;
          hour = hour < 10 ? "0" + hour : hour;
          let minute = this.timestepMinute % 60;
          minute = minute < 10 ? "0" + minute : minute;
          param.step = hour + ":" + minute;
        }
        return param;
      }
      return null;
    },

    startLimitTime() {
      if (this.startLimitDate) {
        let date = anyfishUI.api.getDateByType(this.startLimitDate);
        if (date != null) {
          return date.getTime();
        }
      }
      return 0;
    },

    endLimitTime() {
      if (this.endLimitDate) {
        let date = anyfishUI.api.getDateByType(this.endLimitDate);
        if (date != null) {
          return date.getTime();
        }
      }
      return 0;
    },

    areaArray() {
      if (this.type == "province" || this.type == "city" || this.type == "district") {
        let baseArea = require("../../engine/baseArea");
        let array = [];
        for (let i in baseArea) {
          let srcItem = baseArea[i];
          let item = {};
          item.value = srcItem.n;
          item.label = srcItem.n;
          if (this.type == "city" || this.type == "district") {
            item.children = [];
            for (let j in srcItem.c) {
              let srcSubItem = srcItem.c[j];
              let subItem = {};
              subItem.value = srcSubItem.n;
              subItem.label = srcSubItem.n;
              if (this.type == "district") {
                subItem.children = [];
                for (let k in srcSubItem.c) {
                  let srcPopItem = srcSubItem.c[k];
                  let popItem = {};
                  popItem.value = srcPopItem.n;
                  popItem.label = srcPopItem.n;
                  subItem.children.push(popItem);
                }
              }
              item.children.push(subItem);
            }
          }
          array.push(item);
        }
        return array;
      }
      return null;
    }
  },

  watch: {
    obj() {
      this.register();
    },

    objKey() {
      this.register();
    },

    type() {
      this.changeClick(null);
    }
  },

  mounted() {
    this.register();
  },

  destroyed() {
    this.obj._unRegister(this.objKey);
  },

  methods: {
    register() {
      let self = this;
      this.obj._watch(this.objKey, function (value, srcValue) {
        if (self.type == "time") {
          if (srcValue instanceof Date) {
            self.elValue = srcValue;
            return;
          }
          if (value) {
            self.elValue = anyfishUI.api.getDateByType(value);
            return;
          }
        }
        self.elValue = value;
      }, function (value) {
        if (self.type == "time") {
          if (value && typeof value != "string") {
            return anyfishUI.api.getFormatTime(value, "HH:mm:ss");
          }
        }
        return value;
      });
      this.obj._register(this.objKey, function () {
        let prefix = self.prefix;
        if (!prefix) {
          let type = self.type;
          if (type == "year" || type == "month" || type == "date" || type == "datetime") {
            prefix = "日期";
          } else if (type == "time" || type == "timestep") {
            prefix = "时间";
          } else if (type == "province" || type == "city" || type == "district") {
            prefix = "地区";
          } else {
            prefix = "内容";
          }
        }
        return self.checkData(self.obj[self.objKey], self.required, prefix);
      });
    },

    checkData(data, required, prefix) {
      if (!required) {
        return true;
      }
      if (data == undefined || data == null) {
        anyfishUI.api.toast("请选择" + prefix);
        return false;
      }
      if ((typeof data == "string" ? data.trim() : data + "").length < 1) {
        anyfishUI.api.toast("请选择" + prefix);
        return false;
      }
      return true;
    },

    changeClick(value) {
      this.obj[this.objKey] = value;
      this.$emit("change", value);
    }
  }
}
</script>

<style scoped>
.any-outsidebar {
  margin: 0.5rem 1rem;
  display: flex;
  flex-wrap: nowrap;
  flex-direction: row;
  align-items: center;
}

.any-prefix2 {
  margin-right: 0.5rem;
  font-size: 0.8rem;
  text-align: center;
  white-space: nowrap;
  user-select: none;
  -webkit-user-select: none;
}

.any-prefix {
  margin-right: 0.5rem;
  font-size: 0.8rem;
  text-align: center;
  white-space: nowrap;
  user-select: none;
  -webkit-user-select: none;
}

.any-prefix::before {
  margin: 1px;
  color: #ee0a24;
  font-size: 14px;
  content: "*";
}
</style>